package id.co.shuba.spamobile.widget;

import id.co.shuba.spamobile.R;
import id.co.shuba.spamobile.task.BaseProgressTask;
import id.co.shuba.spamobile.task.OnProgressChangedListener;
import id.co.shuba.spamobile.task.OnStatusChangedListener;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class ProgressAdapter extends BaseAdapter {
	private ArrayList<BaseProgressTask> _list;	
	private Activity _activity;
	private int _icon;

	public ProgressAdapter(Activity activity,ArrayList<BaseProgressTask> list, int icon) {
		super();
		_list = list;		
		_activity = activity;
		_icon = icon;
	}

	public int getCount() {		
		return _list.size();
	}

	public String getItem(int position) { 
		return _list.get(position).toString();
	}	

	public long getItemId(int position) {
		return 0;
	}	

	public View getView(int position, View convertView, ViewGroup parent) {		
		ProgressItemHolder view;
		LayoutInflater inflator = _activity.getLayoutInflater();

		if(convertView==null)
		{
			view = new ProgressItemHolder();
			convertView = inflator.inflate(R.layout.progress_item, null);

			view.icon = (ImageView) convertView.findViewById(R.id.icon);
			view.progress = (ProgressBar) convertView.findViewById(R.id.progress);
			view.title = (TextView) convertView.findViewById(R.id.txtTitle);
			view.status = (TextView) convertView.findViewById(R.id.txtStatus);
			view.position = position;

			convertView.setTag(view);
		}
		else
		{
			view = (ProgressItemHolder) convertView.getTag();
		}
		
		final ProgressItemHolder v = view;		
		
		BaseProgressTask task = _list.get(position);
		v.title.setText(task.getTitle());		
		v.progress.setProgress(task.getProgress());
		v.status.setText(task.getStatusMessage());
		v.icon.setImageResource(_icon);
		//final int pos = position;
		
		task.setProgressChangedListener(new OnProgressChangedListener() {			
			@Override
			public void onProgressChanged(int progress) {
				//if (v.position == pos)
					v.progress.setProgress(progress);
			}					
		});
				
		task.setStatusListener(new OnStatusChangedListener() {			
			@Override
			public void onStatusChanged(final String status) {				
				v.status.post(new Runnable() {					
					@Override
					public void run() {
						//if (v.position == pos)
							v.status.setText(status);
					}
				});
			}
		});						
		
		return convertView;
	}
	
	static class MyOnStatusProgressChangedListener implements OnProgressChangedListener {
		ProgressItemHolder holder;
		int position;
		
		@Override
		public void onProgressChanged(int progress) {
			
		}
	
	}
}
